package com.study.config;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.net.InetSocketAddress;
import java.net.Proxy;

/**
 * @Author hupengming
 * @ClassName
 * @Date 2022-11-14 16:31
 * @Version 1.0
 */
@Data
@Configuration
public class ProxyConfig {

    @Value(value = "${mini.proxy.host:null}")
    private String host;

    @Value(value = "${mini.proxy.port:0}")
    private Integer port;

    @Bean
    public RestTemplate restProxyTemplate() {
        SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        simpleClientHttpRequestFactory.setConnectTimeout(60000);
        simpleClientHttpRequestFactory.setReadTimeout(60000);
        if (StringUtils.isNotBlank(host) && port > 0) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
            simpleClientHttpRequestFactory.setProxy(proxy);
        }
        return new RestTemplate(simpleClientHttpRequestFactory);
    }

}
